package com.ff.xyh.front.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ff.xyh.common.entity.post.PostJoiner;
import com.ff.xyh.common.entity.post.PostReply;
import com.ff.xyh.common.entity.result.ResultCode;
import com.ff.xyh.common.entity.result.ResultMessage;
import com.ff.xyh.common.entity.result.ResultObject;
import com.ff.xyh.common.qo.message.RoomMessageQuery;
import com.ff.xyh.common.vo.post.PostShopVo;
import com.ff.xyh.common.vo.post.PostTravelVo;
import com.ff.xyh.common.qo.post.PostShopQuery;
import com.ff.xyh.common.qo.post.PostTravelQuery;
import com.ff.xyh.front.service.PostFeignService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @Auther FF
 * @Date 2022年 11月 15日
 * @Time 18:13
 */

@Api(tags = "帖子相关接口")
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/post")
public class PostFeignController {

    @Autowired
    private PostFeignService service;

    @PostMapping("shop/get")
    ResultObject getPostShopCondition(
            @RequestBody PostShopQuery postShopQuery) {
        return service.getPostShopCondition(postShopQuery);
    }

    @ApiOperation(value = "条件查询拼购帖")
    @PostMapping("travel/get")
    ResultObject getPostTravelCondition(
            @RequestBody PostTravelQuery postTravelQuery) {
        return service.getPostTravelCondition(postTravelQuery);
    }

    @ApiOperation(value = "通过 postId 和 type 获取帖子详情(信息，照片集，回复集，参与者)")
    @PostMapping("get")
    ResultObject getPost(
            @RequestBody String postIdAndPostTypeJson) {
        JSONObject jsonObject = JSON.parseObject(postIdAndPostTypeJson);
        return service.getPost(jsonObject.getString("postId"), Integer.parseInt(jsonObject.getString("postType")));
    }

    @ApiOperation(value = "添加拼购帖 (消费等级: leastOnce * price)->level: 0<100 1<200 2<500 3<1000")
    @PostMapping("shop/add")
    ResultObject addPostShop(
            @ApiParam(value = "需要 post，level，postImgList")
            @RequestBody PostShopVo postShopVo) {
        System.out.println(postShopVo);
//        postShop.setCheckStatus(0);
//        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(postShopVo));
//        int level = Integer.parseInt(jsonObject.getString("level"));
//        System.out.println(jsonObject.getString("post"));
//        PostShop postShop = JSON.parseObject(jsonObject.getString("post"), PostShop.class);
//        List<PostImg> postImgs = JSON.parseArray(jsonObject.getString("postImgList"), PostImg.class);
        return service.addPostShop(postShopVo);
    }


    @ApiOperation(value = "添加旅游 consumePrice->level: 0<100 1<200 2<500 3<1000")
    @PostMapping("travel/add")
    ResultObject addPostTravel(
            @ApiParam(value = "需要 post，level，postImgList")
            @RequestBody PostTravelVo postTravelVo) {
        System.out.println(postTravelVo);
//        postTravel.setCheckStatus(0);
        return service.addPostTravel(postTravelVo);
    }

//    @Autowired
//    private RedisTemplate redisTemplate;
//    @ApiOperation(value = "测试redis")
//    @PostMapping("test/redis/{value}")
//    Boolean testRedis(@PathVariable String value) {
//        redisTemplate.opsForValue().set("test", value);
//
//        return redisTemplate.hasKey("test");
//    }

//    @ApiOperation(value = "测试rabbit队列功能")
//    @PostMapping("rabbit")
//    ResultObject rabbit(
//            @ApiParam(value = "照片集 数组对象 只须传入每个对象的imgUrl")
//            @RequestBody PostImg[] postImgs) {
//        for (PostImg postImg : postImgs) {
//            postImg.setPostType(1);
//            if (! StringUtils.isEmpty(postImg.getImgUrl())) {
//                rabbitTemplate.convertAndSend(RabbitMqPostConfig.Exchange_Post, RabbitMqPostConfig.Routing_Key, postImg);
//            }
//        }
//        return ResultObject.ok().message("访问陈宫");
//    }


    @ApiOperation(value = "修改拼购帖 请求头中isImgChanged为1则更新照片集")
    @PostMapping("shop/update")
    ResultObject updatePostShop(
            @ApiParam(value = "post的id和被修改的信息, postImgList(请求头中isImgChanged为1则更新照片集)")
            @RequestBody PostShopVo postVo,
            HttpServletRequest request) {
//        postShop.setCheckStatus(0);

        return service.updatePostShop(postVo, request);
    }
    @ApiOperation(value = "修改旅游帖 请求头中isImgChanged为1则更新照片集")
    @PostMapping("travel/update")
    ResultObject updatePostTravel(
            @ApiParam(value = "post的id和被修改的信息, postImgList(请求头中isImgChanged为1则更新照片集)")
            @RequestBody PostTravelVo postVo,
            HttpServletRequest request) {
//        postShop.setCheckStatus(0);

        return service.updatePostTravel(postVo, request);
    }

    @ApiOperation(value = "添加帖子回复")
    @PostMapping("reply/add")
    ResultObject addPostReply(
            @ApiParam(value = "需要postId，postType, userId，content。一级回复不需要parentId")
            @RequestBody PostReply postReply) {
        if (postReply.getParentId() == null) {
            postReply.setParentId("0");
        }
        return service.addPostReply(postReply);
    }
    @ApiOperation(value = "根据id删除回复")
    @PostMapping("reply/delete")
    ResultObject deletePostReply(
            @ApiParam(value = "post的id和被修改的信息, postImgList(请求头中isImgChanged为1则更新照片集)")
            @RequestParam String id) {
        return service.deletePostReply(id);
    }

    /**
     * 参与拼单 TODO 添加队列做超时失效处理。
     * @param joiner
     * @return
     */
    @ApiOperation(value = "添加参与者")
    @PostMapping("joiner/add")
    ResultObject addPostJoiner(
            @RequestBody PostJoiner joiner) {
        return service.addPostJoiner(joiner);
    }
    @ApiOperation(value = "是否申请过")
    @PostMapping("joiner/has")
    ResultObject hasPostJoiner(
            @RequestParam("postId") String postId,
            @RequestParam("postType") Integer postType,
            @RequestParam("userId") String userId) {
        return service.hasPostJoiner(
                postId, postType, userId);
    }
    @ApiOperation(value = "参与者修改拼单数量")
    @PostMapping("joiner/changeUserNumber")
    ResultObject changeJoinerUserNumber(
            @RequestParam("postId") String postId,
            @RequestParam("postType") Integer postType,
            @RequestParam("userId") String userId,
            @RequestParam("number") Integer number) {
        return service.changeJoinerUserNumber(
                postId, postType, userId, number);
    }
    @ApiOperation(value = "接受参与请求")
    @PostMapping("joiner/accept")
    ResultObject acceptPostJoiner(
            @RequestParam("postId") String postId,
            @RequestParam("postType") Integer postType,
            @RequestParam("userId") String userId) {
        return service.acceptPostJoiner(postId, postType, userId);
    }
    @ApiOperation(value = "拒绝参与请求")
    @PostMapping("joiner/refuse")
    ResultObject refusePostJoiner(
            @RequestParam("postId") String postId,
            @RequestParam("postType") Integer postType,
            @RequestParam("userId") String userId) {
        return service.refusePostJoiner(postId, postType, userId);
    }
    @ApiOperation(value = "删除参与者")
    @PostMapping("joiner/delete")
    ResultObject deletePostJoiner(
            @RequestParam("postId") String postId,
            @RequestParam("postType") Integer postType,
            @RequestParam("userId") String userId) {
        return service.deletePostJoiner(postId, postType, userId);
    }
    @ApiOperation(value = "参与者退出参与")
    @PostMapping("joiner/cancel")
    ResultObject cancelPostJoiner(
            @RequestParam("postId") String postId,
            @RequestParam("postType") Integer postType,
            @RequestParam("userId") String userId) {
        return service.cancelPostJoiner(postId, postType, userId);
    }

    @ApiOperation(value = "是否可在xx房间发言")
    @PostMapping("room/speakable")
    ResultObject isUserSpeakableInRoom(
            @RequestParam("postId") String postId,
            @RequestParam("postType") Integer postType,
            @RequestParam("userId") String userId) {
        return service.isUserSpeakable(postId, postType, userId);
    }

//    @ApiOperation(value = "分页获取群聊消息：进入房间时，获取第一页数据，不用messageId，" +
//            "将得到的消息中最新的消息的id存储起来，查询第N页数据时，将id传入")
//    @PostMapping("room/message")
//    ResultObject getRoomMessage(
//            @RequestParam("currentPage") long currentPage,
//            @RequestParam("pageSize") long pageSize,
//            @RequestParam("roomId") String roomId,
//            @RequestParam(name = "messageId", required = false) String messageId) {
//        return service.getRoomMessage(currentPage, pageSize, roomId, messageId);
//    }

    @ApiOperation(value = "条件查询群聊消息")
    @PostMapping("room/message")
    ResultObject getRoomMessageListCondition(
            @RequestBody RoomMessageQuery roomMessageQuery) {
        return service.getRoomMessageListCondition(roomMessageQuery);
    }


    /** 以下是特殊接口 */

    @ApiOperation(value = "上传封面照片 需要type 如果为第二次提交 则需要加入uuid")
    @PostMapping("upload/cover")
    ResultObject uploadPostCover(
            @RequestParam("cover") MultipartFile cover,
            @RequestParam("length") long length,
            @RequestParam("type") String type,
            @RequestParam(name = "uuid", required = false) String uuid) {
//        System.out.println(type + " dddd " + multipartFile);
//        MultipartFile anotherFile = new CommonsMultipartFile(multipartFile.getInputStream());
        System.out.println("type: --> " + type);
        System.out.println("uuid: --> " + uuid);
        System.out.println("length: --> " + length);
        if ( length < 1 || length > 9) {
            return ResultObject.error().message(ResultMessage.ERROR_ARG);
        }
        return service.uploadPostCover(cover, type, uuid);
    }

    @ApiOperation(value = "上传帖子照片 需要type,照片集的长度")
    @PostMapping("upload/img")
    ResultObject uploadPostImg(
            @RequestParam("img") MultipartFile img,
            @RequestParam("type") String type,
            @RequestParam(name="uuid", required = false) String uuid,
            @RequestParam("length") long length
    ) {
//        System.out.println("type: --> " + type);
//        System.out.println("uuid: --> " + uuid);
//        System.out.println("length: --> " + length);

        // 小于1 1张都没 需要返回错误 大于9, 总共超过9张
        if ( length < 1 || length > 9) {
            return ResultObject.error().message(ResultMessage.ERROR_ARG);
        }
        ResultObject resultObject = service.uploadPostImg(img, type, uuid);
        if (resultObject.getCode().equals(ResultCode.SUCCESS_CODE))
            resultObject.data("uuid", uuid);
        return resultObject;
    }

    @ApiOperation(value = "发布失败, 照片上传出错或帖子和帖子照片集上传出错则判定为发布失败")
    @PostMapping("failedAdd")
    ResultObject failedAdd(
            @RequestParam("postId") String postId,
            @RequestParam("type") String type,
            @RequestParam("uuid") String uuid
    ) {
        System.out.println("postId: --> " + postId);
        System.out.println("type: --> " + type);
        System.out.println("uuid: --> " + uuid);
        if (StringUtils.isEmpty(type) || StringUtils.isEmpty(uuid)) {
            return ResultObject.error().message(ResultMessage.ERROR_ARG);
        }
        return service.failedAdd(postId, type, uuid);
    }

    @ApiOperation(value = "删除文件 传入具体路径和文件名 如 xxx/xx/xxx.png")
    @PostMapping("delete/imgInPath")
    ResultObject deleteImgInPath(
            @RequestParam("path")String path) {
        return service.deleteImgInPath(path);
    }

    @ApiOperation(value = "删除文件目录 传入目录路径 如 xxx/xx")
    @PostMapping("delete/imgsInPath")
    ResultObject deleteImgsInPath(
            @RequestParam("path")String path) {
        return service.deleteImgsInPath(path);
    }



}
